package liyan.shi.springboot.controller;

import liyan.shi.springboot.dao.DepartmentDao;
import liyan.shi.springboot.dao.EmployeeDao;
import liyan.shi.springboot.entities.Department;
import liyan.shi.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    /**
     * 查询所有员工
     *
     * @param model
     * @return
     */
    @GetMapping("/emps")
    public String list(Model model) {

        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps", employees);

        return "emp/list";
    }

    /**
     * 转到添加员工页面
     *
     * @return java.lang.String
     * @author shily
     * @date 2018/11/25 19:06
     * @param model
     */
    @GetMapping("/emp")
    public String toAddPage(Model model) {
        //查询页面所有部门, 在新增页面使用
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);

        return "emp/add";
    }

    @PostMapping("/emp")
    //SpringMvc自动将请求参数和入参对象进行一一绑定
    //请求参数的名字和javaBean对象的属性名一致
    public String addEmp(Employee employee){
        System.out.println(employee);
        employeeDao.save(employee);
        //来到员工列表页面
        //redirect:url 表示重定向到一个地址
        //forward:url 表示转发到一个地址
        // '/' 表示当前项目根路径
        return "redirect:/emps";
    }

    //跳转修改页面
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable(value = "id") Integer id, Model model){
        //根据员工号查出员工
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp", employee);
        //查询页面所有部门, 在新增页面使用
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
        //跳转修改页面,重用add页面
        return "emp/add";
    }

    //保存修改
    @PutMapping("/emp")
    public String updateEmployee(Employee employee){
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    //员工删除
    @DeleteMapping("/emp/{id}")
    public String deleteEmployee(@PathVariable(value = "id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

}
